package com.mqb.handler.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mqb.*;
import com.mqb.session.UserSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class LoginMsgInboundHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(LoginMsgInboundHandler.class);

    // private UserService

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        JSONObject jsonObject = JSON.parseObject(msg.toString());
        if (MsgType.isLogin(jsonObject.getString(MsgConstant.MSG_TYPE))) {
            LoginMsg loginMsg = JSON.parseObject(msg.toString(), LoginMsg.class);
            // 判断用户名密码

            // 假装登陆成功
            log.info("[{}] 登陆成功....{}", loginMsg.getEntity().getUserId(), ctx.channel());
            UserSession.add(loginMsg.getEntity().getUserId(), ctx.channel());

            // 创建ackMsg，告诉客户端登陆成功了
            AckMsg ackMsg = new AckMsg(loginMsg.getId(), loginMsg.getSendId(), MsgConstant.SERVER, Result.success(""));
            ctx.writeAndFlush(JSONObject.toJSONString(ackMsg));
        } else {
            RequestMsg requestMsg = JSON.parseObject(msg.toString(), RequestMsg.class);
            super.channelRead(ctx, requestMsg);
        }

    }
}
